<template>
  <div
    class="container"
    :style="'background-image:url(' + bg + ')'"
    @mousedown="onMousedown"
    @mousemove="onMouseMove"
    @mouseup="onMouseUp"
    ref="container"
  ></div>
  <div v-if="showToolbar" class="toolbar" :style="toolbarStyle">
    <span class="iconfont icon-xiazai text-fontPrimary" @click="download"></span>
    <span class="iconfont icon-quxiao text-red-500" @click="cancelSelection"></span>
    <span class="iconfont icon-queren text-fontPrimary" @click="confirmSelection"></span>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { Base64ToFile } from "@/utils/file";
import Konva from "konva";

interface IRectOption {
  x: number;
  y: number;
}

let bg = ref("");
let isDown = false;
let showToolbar = ref(false);
let toolbarStyle = ref({});
let rectOption: IRectOption = { x: 0, y: 0 };
let container = ref<HTMLDivElement | null>(null);
let stage: Konva.Stage | undefined, layer: Konva.Layer, rect: Konva.Rect, transformer: any;

onMounted(() => {
  window.electronApi.showScreenShot();
  window.electronApi.getScreenSouce(getSource);
});

async function getSource(result: any) {
  bg.value = result;
  render();
}

function render() {
  stage = createStage();
  if (!stage) return;
  layer = createLayer(stage);
}

// 创建statge
function createStage() {
  if (!container.value) return;
  return new Konva.Stage({
    container: container.value,
    width: window.innerWidth,
    height: window.innerHeight,
  });
}

// 创建画布
function createLayer(stage: Konva.Stage): Konva.Layer {
  let layer = new Konva.Layer();
  stage.add(layer);
  layer.draw();
  return layer;
}

// 创建矩形
function createRect(
  _layer: Konva.Layer,
  x: number,
  y: number,
  width: number,
  height: number,
  alpha: number,
  draggable: boolean,
) {
  let rectangle = new Konva.Rect({
    x: x,
    y: y,
    width: width,
    height: height,
    fill: "rgba(0,0,255," + alpha + ")",
    draggable: draggable,
  });
  _layer.add(rectangle);
  _layer.draw();
  return rectangle;
}

// 创建可移动图层
function createTransformer(rect: Konva.Rect) {
  let transformer = new Konva.Transformer({
    nodes: [rect],
    rotateAnchorOffset: 60,
    enabledAnchors: ["top-left", "top-right", "bottom-left", "bottom-right"],
  });
  return transformer;
}

// 鼠标左键按下的时候
function onMousedown(e: MouseEvent) {
  if (rect || isDown) return;
  isDown = true;
  const { pageX, pageY } = e;
  rectOption.x = pageX || 0;
  rectOption.y = pageY || 0;
  rect = createRect(layer, pageX, pageY, 0, 0, 0.25, false);
}

// 鼠标开始移动的时候
function onMouseMove(e: MouseEvent) {
  if (!isDown || !rect) return;
  const { pageX, pageY } = e;
  let w = pageX - rectOption.x;
  let h = pageY - rectOption.y;
  rect.remove();
  rect = createRect(layer, rectOption.x, rectOption.y, w, h, 0.25, false);
  rect.draw();
}

// 鼠标左键抬起的时候
function onMouseUp(e: MouseEvent) {
  if (!isDown || !rect) return;
  isDown = false;
  const { pageX, pageY } = e;
  let w = pageX - rectOption.x;
  let h = pageY - rectOption.y;
  rect.remove();
  rect = createRect(layer, rectOption.x, rectOption.y, w, h, 0, true);
  rect.draw();
  transformer = createTransformer(rect);
  layer.add(transformer);
  showToolbar.value = true;
  updateToolbarPosition(rectOption.x, rectOption.y, w, h);
  // 监听rect拖动，实时更新toolbar位置
  rect.on("dragmove", () => {
    const { x, y, width, height, scaleX = 1, scaleY = 1 } = rect.attrs;
    updateToolbarPosition(x, y, width * scaleX, height * scaleY);
  });
  // 改变大小的是时候，实时更新toolbar位置
  rect.on("transform", () => {
    const { x, y, width, height, scaleX = 1, scaleY = 1 } = rect.attrs;
    updateToolbarPosition(x, y, width * scaleX, height * scaleY);
  });
}

// 更新tollBar位置
function updateToolbarPosition(x: number, y: number, w: number, h: number) {
  const toolbarWidth = 160; // 3 icons * 40px + gap/padding
  const toolbarHeight = 50;
  let toolbarLeft = x + w / 2 - toolbarWidth / 2;
  let toolbarTop = y + h + 10;

  // 边界处理：右边
  if (toolbarLeft + toolbarWidth > window.innerWidth) {
    toolbarLeft = window.innerWidth - toolbarWidth - 10;
  }
  // 边界处理：左边
  if (toolbarLeft < 0) {
    toolbarLeft = 10;
  }
  // 边界处理：下边
  if (toolbarTop + toolbarHeight > window.innerHeight) {
    toolbarTop = y - toolbarHeight - 10;
    if (toolbarTop < 0) toolbarTop = 10;
  }

  toolbarStyle.value = {
    left: `${toolbarLeft}px`,
    top: `${toolbarTop}px`,
  };
}

// 获取截图的数据
async function getCutImage() {
  const { width, height, x, y, scaleX = 1, scaleY = 1 } = rect.attrs;
  const _x = width > 0 ? x : x + width * scaleX;
  const _y = height > 0 ? y : y + height * scaleY;
  const w = Math.abs(width) * scaleX;
  const h = Math.abs(height) * scaleY;

  const loadImage = (src: string): Promise<HTMLImageElement> =>
    new Promise((resolve, reject) => {
      const img = new Image();
      img.onload = () => resolve(img);
      img.onerror = reject;
      img.src = src;
    });

  const img = await loadImage(bg.value);
  const canvas = document.createElement("canvas");
  canvas.width = w;
  canvas.height = h;
  const ctx = canvas.getContext("2d");
  if (!ctx) return;
  ctx.drawImage(img, -_x, -_y, window.innerWidth, window.innerHeight);
  return canvas.toDataURL("image/png");
}

// 下载截图
async function download() {
  let data = await getCutImage();
  if (!data) return;
  const { name, type } = Base64ToFile(data);
  window.electronApi.fileSave({
    fileName: name,
    fileType: type,
    url: data,
  });
}

// 确认截图
async function confirmSelection() {
  let data = await getCutImage();
  if (!data) return;
  showToolbar.value = false;
  window.electronApi.confirmSceenShot(data);
}

// 取消截图
function cancelSelection() {
  showToolbar.value = false;
  window.electronApi.closeScreenShot();
}
</script>

<style lang="scss" scoped>
.container {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: transparent;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  border: 2px solid #07c160;
  box-sizing: border-box;
}
.toolbar {
  position: absolute;
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 10px;
  background-color: var(--bg-center);
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 10000000000000000000000;
  cursor: pointer;
  span {
    width: 40px;
    text-align: center;
    font-size: 18px;
    color: var(--font-primary);
  }
}
</style>
